gtmpl-rust – Golang Templates for Rust
gtmpl-rust provides the Golang text/template engine for Rust. This enables seamless integration of Rust application into the world of devops tools around kubernetes, docker and whatnot.
Getting Started
Add the following dependency to your Cargo manifest…
[]
= "0.5.7"
and look at the docs:
It's not perfect, yet. Help and feedback is more than welcome.
Some Examples
Basic template:
extern crate gtmpl;
use gtmpl;
Adding custom functions:
extern crate gtmpl;
extern crate gtmpl_value;
use Function;
use ;
Passing a struct as context:
extern crate gtmpl;
extern crate gtmpl_derive;
extern crate gtmpl_value;
Invoking a method on a context:
extern crate gtmpl;
extern crate gtmpl_derive;
extern crate gtmpl_value;
use ;
Current Limitations
This is work in progress. Currently the following features are not supported:
- complex numbers
- the following functions have not been implemented:
html
,js
printf
is not yet fully stable, but should support all sane input
Enhancements
Even though it was never intended to extend the syntax of Golang text/template there might be some convenient additions:
Dynamic Template
Enable gtmpl_dynamic_template
in your Cargo.toml
:
[]
= "0.5.7"
= ["gtmpl_dynamic_template"]
Now you can have dynamic template names for the template
action.
Example
extern crate gtmpl;
use ;
The following syntax is used:
{{template (pipeline)}}
The template with the name evaluated from the pipeline (parenthesized) is
executed with nil data.
{{template (pipeline) pipeline}}
The template with the name evaluated from the first pipeline (parenthesized)
is executed with dot set to the value of the second pipeline.
Context
We use gtmpl_value's Value as internal data type. gtmpl_derive provides a
handy derive
macro to generate the From
implementation for Value
.
See:
- gtmpl_value at crates.io
- gtmpl_value documentation
- gtmpl_derive at crates.io
- gtmpl_derive documentation
Why do we need this?
Why? Dear god, why? I can already imagine the question coming up why anyone would ever do this. I wasn't a big fan of Golang templates when i first had to write some custom formatting strings for docker. Learning a new template language usually isn't something one is looking forward to. Most people avoid it completely. However, it's really useful for automation if you're looking for something more lightweight than a full blown DSL.
The main motivation for this is to make it easier to write devops tools in Rust that feel native. docker and helm (kubernetes) use golang templates and it feels more native if tooling around them uses the same.